//
//  UIKZeroView.swift
//  Preferential
//
//  Created by Fineland on 2021/3/19.
//

enum UIKZeroViewType: String {
    
    case recordset = "system_zero_recordset"
    case serverError = "system_zero_server_error"
    case unknow
}

// MARK: -

class UIKZeroView: UILabel {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置属性
        self.font = UIFont.systemFont(ofSize: 14.0)
        self.textAlignment = .center
        self.textColor = UIColor.gray
        self.numberOfLines = 0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    func showType(_ type: UIKZeroViewType, with infoText: String) -> Void {
        
        //图片
        let img = UIImage(named: type.rawValue)!
        let attachment = NSTextAttachment()
        attachment.bounds = CGRect(origin: CGPoint(x: 0.0, y: -3.0), size: img.size)
        attachment.image = img
        //值
        let tempVal = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        tempVal.append(NSAttributedString(string: "\n\n" + infoText))
        //显示
        self.attributedText = tempVal
    }
}

// MARK: -

private struct AssociatedKey {
    
    //请求等待
    static var ZERO: String = "Recordset_Zero"
}

// MARK: -

extension UIViewController {
    
    private var zeroView: UIKZeroView? {
        
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.ZERO) as? UIKZeroView
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.ZERO, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func showZero(_ isZero: Bool = true, to type: UIKZeroViewType = .recordset,
                  with infoText: String = "opps！暂无记录~", yoffset: CGFloat = 0.0) -> Void {
        
        //是否需要显示？
        if true != isZero {
            if nil != self.zeroView {
                self.zeroView!.isHidden = true
            }
            return
        }
        //是否为空？
        if nil == self.zeroView {
            //RECT值
            let rect = self.navigationController!.view.bounds
            let hVal: CGFloat = 124.0
            //y值是否大于0？
            let tempVal = yoffset > 0.0 ? yoffset : (0.2 * rect.size.height)
            let tempView = UIKZeroView(frame: CGRect(x: 0.0, y: tempVal, width: rect.size.width, height: hVal))
            self.zeroView = tempView
            //添加
            self.view.addSubview(tempView)
        }
        //显示
        self.zeroView!.showType(type, with: infoText)
        self.zeroView!.isHidden = false
    }
}
